package barinadroid.game;

import org.andengine.entity.primitive.Rectangle;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.util.color.Color;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;

public class Enemy extends GameEntity
{
	private float life;
	private Behavior behavior;

	public Enemy()
	{
		PhysicsWorld physicsWorld = GameScene.getSharedInstance().getPhysicsWorld();
		this.sprite = new Rectangle(0, 0, 50, 50, GameActivity.getSharedInstance().getVertexBufferObjectManager());
		this.sprite.setRotationCenter(sprite.getWidth() * .5f, sprite.getHeight() * .5f);
		this.sprite.setColor(Color.RED);
		attachChild(sprite);
		setBody(EntityIdentity.ENEMY);
		physicsWorld.registerPhysicsConnector(new PhysicsConnector(this.sprite, this.body, true, true));
		this.reset();
	}

	public void reset()
	{
		clearEntityModifiers();
		this.sprite.clearEntityModifiers();
		setBehavior(null);
		this.life = 1;
	}

	// @Override
	// void setBody(FixtureDef def)
	// {
	// this.body =
	// PhysicsFactory.createBoxBody(GameScene.getSharedInstance().getPhysicsWorld(),
	// sprite, BodyType.DynamicBody, def);
	// this.body.setUserData(this);
	// }
	@Override
	void setBody(EntityIdentity identity)
	{
		this.body = PhysicsFactory.createBoxBody(GameScene.getSharedInstance().getPhysicsWorld(), sprite, BodyType.DynamicBody, identity.getFixtureDef());
		this.body.setUserData(this);
		setEntityIdentity(identity);
	}

	public Behavior getBehavior()
	{
		return this.behavior;
	}

	/***
	 * Will set a new {@link Behavior} to the {@link Enemy} replacing old one.
	 * 
	 * @param behavior
	 *            the desired {@link Behavior}. pass '<code>null</code>' to
	 *            clear current {@link Behavior}(if any).
	 */
	public void setBehavior(Behavior behavior)
	{
		if(this.behavior != null)
			unregisterUpdateHandler(this.behavior.getUpdateHandler());
		getBody().setLinearVelocity(0, 0);
		getBody().setAngularVelocity(0);
		getBody().setAngularDamping(0);
		this.behavior = behavior;
	}

	public Bullet Shoot()
	{
		Bullet bullet = BulletFactory.getSharedInstance().Shoot(this);
		// bullet.setPositionByCenter(this);
		bullet.setPosition(this);
		return bullet;
	}

	/**
	 * Lower {@link Enemy} life and check if its dead.
	 * 
	 * @return If the {@link Enemy} died in the process.
	 */
	public boolean hit(float amount)
	{
		return (this.life -= amount) <= 0;
	}
}